'''
Author: Ryhn0412
LastEditTime: 2024-04-10 10:59:01
FilePath: \pythonProject1\main.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
import abc
import base64
import datetime
import re
import jira
import requests
from jira import JIRA

# -*- coding: utf-8 -*-
# @Author : Ryhn

class exportMeta(abc.ABC):
     '''
     数据获取的抽象类
     '''
     @abc.abstractmethod
     def GetData(self):
          pass


class Export(exportMeta):
     '''
     数据获取的实现类
     '''
     def __init__(self, type_export):
          self.export = type_export

     def GetData(self):
          '''
          获取数据
          :return:
          '''
          self.export.GetData()

# Todo:jira数据采集类
class jira_export(exportMeta):
     def __init__(self, username: str, password: str, url: str):
          self.auth = (username, password)
          self.url = url
          self.option = JIRA(server=self.url, auth=self.auth)
          self.notifyList = []

     def GetData(self, key):
          '''
          数据获取
          :param key:
          :return:
          '''
          data = self.GetIssus(key)
          question = Issue(data)
          # 实例化bugexplaner, IssueExplaner
          BugEX = BugExplaner()
          IssueExplaner([BugEX]).explanIssue(question, self)
          return BugEX.list, question

     def GetIssus(self, key):
          return self.option.issue(key)

     def header(self):
          text =f"{self.auth[0]}:{self.auth[1]}".encode("utf-8")
          data =base64.b64encode(text)
          return {"Authorization": "Basic "+data.decode("utf-8"),
                  "Content-Type": "application/json"}

# Todo:任务类
class Issue():
     def __init__(self, obj: jira.Issue):
          self.key = None
          self.data = obj
          self.type = None
          self.title = None
          self.description = None
          self.url = None
          self.marker = None
          self.startTime = None
          self.endTime = None
          self.subtasks = None

     def __dict__(self):
          return {"url": self.url, "title": self.title, "key": self.key, "type": self.type, "description": self.description,
                  "marker": self.marker, "startTime": self.startTime, "endTime": self.endTime}

     def __str__(self):
          return f"标题为{self.title},地址为{self.url}"

     def __getattr__(self, name):
          print(f"查询对应属性{name}失败")
          return None

# Todo:任务处理类
class IssueExplaner:
     '''
     问题消息处理者（建造者模式中的厨师角色）
     '''
     def __init__(self, list):
          self.list = list

     def explanIssue(self, obj, option):
          '''
          以建造者模式处理issue类的数据,若是bug类型的type直接消息推送
          :return:
          '''
          [i(obj) for i in
           [self.set_title, self.set_key, self.set_type, self.set_description, self.set_url, self.set_marker, self.set_startTime,
            self.set_endTime, self.set_subtasks]]
          if obj.type == "BUG":
               for i in self.list:
                    i.notify(obj.subtasks, option)

     def set_subtasks(self, issue):
          issue.subtasks = issue.data.fields.subtasks

     def set_type(self, issue):
          issue.type = issue.data.fields.issuetype.name

     def set_title(self, issue):
          summary = issue.data.fields.summary
          result = re.split(r'】', summary)[1]
          issue.title = result

     def set_description(self, issue):
          description = des if (des := issue.data.fields.description) else ""
          issue.description = description

     def set_url(self, issue):
          url = re.findall(r'[htps0-9.:/]+', issue.data.raw.get("self"))[0] + f"browse/{issue.key}"
          issue.url = url

     def set_key(self, issue):
          issue.key = issue.data.key

     def set_marker(self, issue):
          assignee = marker if (marker := issue.data.fields.assignee) else "测试组"
          issue.marker = assignee

     def set_startTime(self, issue):
          time = issue.data.fields.created
          result = re.split(r'T', time)[0]
          issue.startTime = result

     def set_endTime(self, issue):
          issue.endTime = datetime.date.today()

# Todo:子bug类
class Bug():
     def __init__(self, name, type, status, summary, poriety, tester, explaner, kind, explan):
          self.name = name
          self.type = type
          self.status = status
          self.summary = summary
          self.poriety = poriety
          self.tester = tester
          self.explaner = explaner
          self.kind = kind
          self.explan = explan

     def __getattr__(self, name):
          print(f"查询对应属性{name}失败")
          return None

     def __dict__(self):
          return {
               "name": self.name, "type": self.type, "status": self.status, "summary": self.summary,
               "poriety": self.poriety, "tester": self.tester, "explaner": self.explaner, "kind": self.kind, "explan": self.explan
          }

     def __str__(self):
          return f"问题:{self.name},优先级:{self.poriety},状态:{self.status},处理人:{self.explan},所属端:{self.kind}\n"


     def __list__(self):
          return [self.name, self.type, self.poriety,  self.status,  self.explaner]

# Todo:子bug处理类
class BugExplaner:
     def __init__(self):
          self.list = []

     def notify(self, subtasks: list, option: jira_export):
          for i in subtasks:
               raw = requests.get(i.raw['self'], headers=option.header()).json()['fields']
               self.list.append(Bug(name=raw['summary'], type=raw['issuetype']['name'], status=raw['status']['name'],
                                    summary=raw['description'], poriety=raw['priority']['name'], tester=raw['creator']['displayName'],
                                    explaner=raw['assignee']['displayName'], kind=raw['customfield_10801']['value'] if raw.get('customfield_10801') else "", explan=raw['customfield_10802']['value'] if raw.get('customfield_10802') else ""))
